package com.ihealthway.all.groupbuy.services;

import com.ihealthway.all.groupbuy.vo.WinnerLog;
import org.nutz.dao.Cnd;
import org.nutz.dao.Sqls;
import org.nutz.dao.sql.Criteria;
import org.nutz.dao.sql.Sql;
import org.nutz.dao.sql.SqlCallback;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;
import org.nutz.log.Log;
import org.nutz.log.Logs;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * WinnerLog Log service
 *
 * @author 凡梦星尘(elkan1788@gmail.com)
 */
@IocBean(fields = {"dao"})
public class WinnerLogService extends BaseService<WinnerLog> {

    private static final Log logger = Logs.get();

    public List<WinnerLog> getWinLogForFront(Integer userId) {
        List<WinnerLog> winLogs = new ArrayList<>();
        String sqlStmt = "SELECT wl.*, ui.real_name AS uName,rd.rwd_name AS rName,rd.rwd_img AS rImg,rd.rwd_price AS rPrice FROM gb_winner_log AS wl " +
                "LEFT JOIN gb_user_info AS ui ON ui.u_id = wl.u_id " +
                "LEFT JOIN gb_rewards AS rd ON rd.rwd_id = wl.rwd_id $condition";
        Criteria cri = Cnd.cri();
        cri.where().andEquals("wl.u_id", userId);
        Sql sql = Sqls.create(sqlStmt);
        sql.setCondition(cri);
        sql.setCallback(new WinnerLogCallBack());
        dao().execute(sql);
        List<WinnerLog> tmp = sql.getList(WinnerLog.class);
        if (tmp!=null && !tmp.isEmpty()) {
            winLogs.addAll(tmp);
        }
        return winLogs;
    }

    public WinnerLog addWinnerLog(WinnerLog winnerLog) {
        winnerLog.setWinTime(new Date());
        try {
            WinnerLog tmp = dao().fastInsert(winnerLog);
            return tmp;
        } catch (Exception e) {
            logger.error("Can't add winner log!!!", e);
            return null;
        }
    }

    public boolean updateWinnerLog(WinnerLog winnerLog) {

        winnerLog.setWinTime(new Date());
        try {
            int rows = dao().updateIgnoreNull(winnerLog);
            return rows>0;
        } catch (Exception e) {
            logger.error("Can't update winner log!!!", e);
            return false;
        }
    }

    public boolean updateWinnerStatus(String winnerIds, Integer status) {
        boolean updated = false;
        Sql sql = Sqls.create("UPDATE gb_winner_log SET data_status=@dataStatus WHERE " +
                "win_id IN ("+winnerIds+") AND data_status NOT IN (0, 4) ");
        sql.params().set("dataStatus", status);
        try {
            dao().execute(sql);
            updated = true;
        } catch (Exception e) {
            logger.error("Update winner status fail!!!", e);
        }
        return updated;
    }

    public boolean checkWinLog(Integer userId) {
        Criteria cri = Cnd.cri();
        cri.where().andEquals("u_id", userId);
        List<WinnerLog> wl = dao().query(WinnerLog.class, cri);
        if (wl==null||wl.isEmpty()) {
            return false;
        }
        return true;
    }

    public Map<String, Object> getDataList(Integer curPage, Integer pageSize, String userName, String sDate, String eDate) {
        String sqlStmt = "SELECT wl.*, ui.real_name AS uName,rd.rwd_name AS rName,rd.rwd_img AS rImg,rd.rwd_price AS rPrice FROM gb_winner_log AS wl " +
                "LEFT JOIN gb_user_info AS ui ON ui.u_id = wl.u_id " +
                "LEFT JOIN gb_rewards AS rd ON rd.rwd_id = wl.rwd_id $condition";

        Criteria cri = Cnd.cri();
        if (Strings.isNotBlank(userName)) {
            cri.where().andLike("wl.winner_name", userName);
        }

        if (Strings.isNotBlank(sDate) && Strings.isNotBlank(eDate)) {
            cri.where().andBetween("wl.win_time", sDate, eDate);
        }

        return easyuiDGPagerWithFetch(sqlStmt, curPage, pageSize, cri, new WinnerLogCallBack());
    }

    private class WinnerLogCallBack implements SqlCallback {

        @Override
        public Object invoke(Connection conn, ResultSet rs, Sql sql) throws SQLException {
            List<WinnerLog> data = new ArrayList<>();
            while (rs.next()) {
                WinnerLog winLog = getEntity().getObject(rs, null, "wl.");
                winLog.setRewardName(rs.getString("rName"));
                winLog.setUserName(rs.getString("uName"));
                winLog.setRewardPrice(rs.getInt("rPrice"));
                winLog.setRewardImg(rs.getString("rImg"));
                data.add(winLog);
            }
            return data;
        }
    }
}
